package com.xhu.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;

/**
 *   子类的请求路  url-mapping
 *   1.url= 自定义/方法名
 *   2.方法名(HttpServletRequest aaaa)
 */
public class BaseServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //根据你请求路径 来调用对应的方法
        String url=request.getRequestURI();
        //全路径
        System.out.println(url);
        //最后一个/ 后面内容==方法名字
        String methodName=getMethodName(url);
        //反射 得到方法
        Class clazz= this.getClass();
        try {
            //得到本对象的方法
            Method method = clazz.getMethod(methodName, HttpServletRequest.class);
            //调用 方法的返回值
            Object obj = method.invoke(this, request);
            if(obj instanceof  String){
                //转发和重定向  还有文件路径
                String result=(String)obj;
                if(result.contains("redirect:")){
                    response.sendRedirect(result.replace("redirect:",""));
                }else  if(result.contains("forward:")){
                    request.getRequestDispatcher(result.replace("forward:","")).forward(request,response);
                }else if(result.contains("file:")){//file:img/headImg.jpg
                    String path=result.replace("file:","");
                    //提取出绝对路径
                    String  absolutePath=request.getSession().getServletContext().getRealPath(path);
                    //获取输入流 读取文件
                    InputStream in=new BufferedInputStream(new FileInputStream(absolutePath));
                    //把这个文件响应给前端 是以文件传输的方式
                    //设置响应头 告知响应的是一个文件
                    // response.addHeader("Content-Disposition","attachment;fileName="+ FilenameUtils.getName(path));
                    //如果是中文  为了防止乱码 最好设置响应的 文件名的字符编码集
                    response.addHeader("Content-Disposition","attachment;fileName="
                            +new String(FilenameUtils.getName(path).getBytes("utf-8"),"ISO-8859-1"));
                    //真滴把文件响应给浏览器
                    OutputStream out =new BufferedOutputStream(response.getOutputStream()) ;
                    int  i;//边读边写
                    while((i=in.read())!=-1){
                        out.write(i);
                    }
                    out.flush();
                    out.close();
                    in.close();
                }
            }else if(obj instanceof HSSFWorkbook){//poi
                //给出一个Excel文件
                HSSFWorkbook  wkb=(HSSFWorkbook)obj;
                //输出Excel文件
                OutputStream output=response.getOutputStream();
                response.reset();
                //设置响应方式  文件传输
                response.setHeader("Content-disposition", "attachment; filename="+System.currentTimeMillis()+".xls");
                //并说明了文件格式
                response.setContentType("application/msexcel");
                //写入  把当前的 excel写入 OuPut中 :响应对象响应出这个excel对象给浏览器
                wkb.write(output);
                output.close();
            }else{
                //json
                PrintWriter writer = response.getWriter();
                writer.println(JSON.toJSONString(obj));
                writer.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //出现异常
            response.sendRedirect("http://localhost:8181/Manager_war/view/error/500.html");
        }
    }
    private   String  getMethodName(String url){
        //找到最后一个 斜杠下标
        int  index=url.lastIndexOf("/");
        String methodName=url;
        if(index!=-1){
            methodName=url.substring(index+1);
        }
        return   methodName;
    }

}
